using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Weazel.Toad.Application.Items;
using Weazel.Toad.Application.Actions;
using Weazel.Toad.Application.Controls;

using Weazel.Toad.TextEditor.Document;
using Weazel.Toad.TextEditor;

namespace Weazel.Toad.Application.Forms
{
  public partial class MainForm : Form
  {
    #region ToolStrip Management
    private List<ToadToolStrip> toolStrips = new List<ToadToolStrip>();

    public void RegisterToolStrip(ToadToolStrip toolStrip)
    {
      if (!toolStrips.Contains(toolStrip))
      {
        toolStrips.Add(toolStrip);          
        toolStripContainer1.TopToolStripPanel.Controls.Add(toolStrip as ToolStrip);
      }
    }

    public void UnregisterToolStrip(ToadToolStrip toolStrip)
    {
      if (!toolStrips.Contains(toolStrip))
        throw new ArgumentException("ToopStrip not in list");

      toolStrips.Remove(toolStrip);
      toolStripContainer1.TopToolStripPanel.Controls.Remove(toolStrip as ToolStrip);
    }
    #endregion

    private Controls.FileToolStrip.FileToolStrip fileToolStrip;

    //private Controls.MicroblazeToolStrip.MicroblazeToolStrip microblazeToolStrip;
    //public Controls.MicroblazeToolStrip.MicroblazeToolStrip MicroblazeToolStrip
    //{
    //  get { return microblazeToolStrip; }      
    //}

    private Controls.SimulationToolStrip.SimulationToolStrip simulationToolStrip;
    public Controls.SimulationToolStrip.SimulationToolStrip SimulationToolStrip
    {
      get { return simulationToolStrip; }      
    }

    public DefaultLayoutControl LayoutControl
    {
      get 
      { 
        return this.defaultLayoutControl; 
      }
    }

    public TabControl MainTabControl
    {
      get
      {
        return LayoutControl.MainTabControl;
      }
    }

    public ToolStripStatusLabel SimulationStatusPanel
    {
      get
      {
        return this.simulationStatusPanel;
      }
    }

    private Control layoutControl = null;

    public void SetLayoutControl(Control control)
    {
      if (layoutControl != null)
        toolStripContainer1.ContentPanel.Controls.Remove(layoutControl);

      this.layoutControl = control;
      this.layoutControl.Dock = DockStyle.Fill;

      toolStripContainer1.ContentPanel.Controls.Add(control);
    }

    public MainForm()
    {
      InitializeComponent();

      Application.Instance.SelectedItemChanging +=
        new EventHandler<SelectedItemChangedEventArgs>(Instance_SelectedItemChanging);

      Application.Instance.SelectedItemChanged +=
        new EventHandler<SelectedItemChangedEventArgs>(Application_SelectedItemChanged);

      // set a custom toolstrip renderer to get the same
      // color scheme as Visual Studio .NET 2005 (Whidbey)
      ToolStripManager.Renderer = new ToolStripProfessionalRenderer(new WhidbeyColorTable());

      // calculate a size that occupies 90% of the screen area
      Width = (int)(Screen.PrimaryScreen.Bounds.Width * .90);
      Height = (int)(Screen.PrimaryScreen.Bounds.Height * .90);

      //microblazeToolStrip =
      //  new Weazel.Toad.Application.Controls.MicroblazeToolStrip.MicroblazeToolStrip();

      //RegisterToolStrip(microblazeToolStrip);

      simulationToolStrip = 
        new Weazel.Toad.Application.Controls.SimulationToolStrip.SimulationToolStrip();

      RegisterToolStrip(simulationToolStrip);

      fileToolStrip =
        new Weazel.Toad.Application.Controls.FileToolStrip.FileToolStrip();

      RegisterToolStrip(fileToolStrip);
    }

    private void openFiles()
    {
      if (Application.Instance.CommandLineArguments == null)
        return;

      foreach (string filename in Application.Instance.CommandLineArguments)
      {
        if (!System.IO.File.Exists(filename))
        {
          MessageBox.Show(string.Format(" file '{0}' does not exist", filename));
          continue;
        }
        else
        {
          System.IO.FileInfo fi = new System.IO.FileInfo(filename);

          switch (fi.Extension.ToLower())
          {
            case ".vhd":
              VhdlTextFile vhdlTextFile = new VhdlTextFile();
              vhdlTextFile.Filename = filename;
              vhdlTextFile.DisplayName = filename;
              vhdlTextFile.Open();
              Application.Instance.AddOpenItem(vhdlTextFile);
              break;
            case ".fdl":
              GezelTextFile gezelTextFile = new GezelTextFile();
              gezelTextFile.Filename = filename;
              gezelTextFile.DisplayName = filename;
              gezelTextFile.Open();
              Application.Instance.AddOpenItem(gezelTextFile);
              break;
            default:
              TextFile textFile = new TextFile();
              textFile.Filename = filename;
              textFile.DisplayName = filename;
              textFile.Open();
              Application.Instance.AddOpenItem(textFile);
              break;
          }
        }
      }
    }

    private void BindActions()
    {
      foreach (ToadToolStrip toolStrip in toolStrips)
        toolStrip.BindActions();
      
      // synthesis
      ActionBase.Actions[typeof(ConvertToVhdlAction)].BindToolStripItem(synthesizeToolStripMenuItem);
      ActionBase.Actions[typeof(ShowSynthesisOptionsAction)].BindToolStripItem(optionsToolStripMenuItem);
      //ActionBase.Actions[typeof(SynthesizeAsOpbSlaveAction)].BindToolStripItem(synthesizeAsOPBSlaveToolStripMenuItem);

      // bind new project item
      //ActionBase.Actions[typeof(NewProjectAction)].BindToolStripItem(newProjectToolStripButton); 
      //ActionBase.Actions[typeof(NewProjectAction)].BindToolStripItem(newProjectToolStripMenuItem);     
      //ActionBase.Actions[typeof(SaveProjectAction)].BindToolStripItem(saveProjectToolStripMenuItem);
      //ActionBase.Actions[typeof(OpenProjectAction)].BindToolStripItem(openProjectToolStripMenuItem);

      // bind text file operations
      ActionBase.Actions[typeof(NewTextFileAction)].BindToolStripItem(newTextFileToolStripMenuItem);
      ActionBase.Actions[typeof(OpenTextFileAction)].BindToolStripItem(openTextFileToolStripMenuItem);      

      // bind gezel file operations
      ActionBase.Actions[typeof(NewGezelModelAction)].BindToolStripItem(newGezelModelToolStripMenuItem);
      ActionBase.Actions[typeof(OpenGezelModelAction)].BindToolStripItem(openGezelModelToolStripMenuItem);
      
      // bind gezel insert operations
      ActionBase.Actions[typeof(InsertDatapathControllerUsingDialogAction)].BindToolStripItem(gezelUseDialogToAddDatapathToolStripMenuItem);
      ActionBase.Actions[typeof(InsertDatapathFsmSkeletonAction)].BindToolStripItem(gezelInsertFsmSkeletonToolStripMenuItem);
      ActionBase.Actions[typeof(InsertDatapathHardwiredSkeletonAction)].BindToolStripItem(gezelHardwiredSkeletonToolStripMenuItem);
      ActionBase.Actions[typeof(InsertDatapathSequencerSkeletonAction)].BindToolStripItem(gezelInsertSequencerSkeletonToolStripMenuItem);
      ActionBase.Actions[typeof(InsertOpbSlaveIpBlockAction)].BindToolStripItem(xilinxOPBIPIFSlaveToolStripMenuItem);
      ActionBase.Actions[typeof(InsertMemoryIpBlock)].BindToolStripItem(memoryToolStripMenuItem);
      ActionBase.Actions[typeof(InsertSimplifiedOpbSlaveIpBlock)].BindToolStripItem(simplifiedOPBSlaveToolStripMenuItem);
      ActionBase.Actions[typeof(InsertSimplifiedOpbMasterIpBlock)].BindToolStripItem(simplifiedOPBMasterToolStripMenuItem);

      // bind vhdl file operations
      ActionBase.Actions[typeof(NewVhdlFileAction)].BindToolStripItem(newVhdlFileToolStripMenuItem);
      ActionBase.Actions[typeof(OpenVhdlFileAction)].BindToolStripItem(openVhdlFileToolStripMenuItem);

      // bind general actions      
      ActionBase.Actions[typeof(OpenFileAction)].BindToolStripItem(openFileToolStripMenuItem);
      

      ActionBase.Actions[typeof(SaveSelectedItemAction)].BindToolStripItem(saveSelectedItemToolStripMenuItem);
      //	ActionBase.Actions[typeof(SaveSelectedItemAction)].BindToolStripItem(saveSelectedItemToolStripButton);

      ActionBase.Actions[typeof(SaveSelectedItemAsAction)].BindToolStripItem(saveSelectedItemAsToolStripMenuItem);

      ActionBase.Actions[typeof(SaveAllAction)].BindToolStripItem(saveAllToolStripMenuItem);

      ActionBase.Actions[typeof(ShowAboutAction)].BindToolStripItem(aboutToolStripMenuItem1);
      ActionBase.Actions[typeof(ShowSettingsAction)].BindToolStripItem(settingsToolStripMenuItem);

      ActionBase.Actions[typeof(CloseFileAction)].BindToolStripItem(closeFileToolStripMenuItem);

      ActionBase.Actions[typeof(SelectNextOpenItemAction)].BindToolStripItem(nextItemToolStripMenuItem);

      ActionBase.Actions[typeof(ShowVersionHistoryAction)].BindToolStripItem(versionHistoryToolStripMenuItem);

      // editing actions
      ActionBase.Actions[typeof(GotoLineAction)].BindToolStripItem(goToToolStripMenuItem);

      // recent files
      ActionBase.Actions[typeof(OpenRecentFileAction)].BindToolStripItem(recentFilesToolStripMenuItem);

      ActionBase.Actions[typeof(ExitApplicationAction)].BindToolStripItem(exitToolStripMenuItem);
    }

    void Instance_SelectedItemChanging(object sender, SelectedItemChangedEventArgs e)
    {
      //if (e.SelectedItem is GezelTextFile)
      //{
      //  GezelTextFile gezelFile = e.SelectedItem as GezelTextFile;

      //  validateCycleCount();
      //  gezelFile.Simulation.CyclesToRun = cyclesToRun;
      //}
    }

    /// <summary>
    /// TODO: Move funcionality in this method to coressponding action.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Application_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e)
    {
      ItemBase item = e.SelectedItem;
      if (item != null && item.CanSave)
      {
        saveSelectedItemToolStripMenuItem.Text = string.Format("Save '{0}'", item.DisplayName);
      }
      else
      {
        saveSelectedItemToolStripMenuItem.Text = "Save";
      }
      
      //if (item is GezelTextFile)
      //{
      //  GezelTextFile gezelFile = item as GezelTextFile;

      //  // enable VHDL conversion
      //  simulationCyclesTextBox.Enabled = true;
      //  cyclesToRun = gezelFile.Simulation.CyclesToRun;
      //  simulationCyclesTextBox.Text = gezelFile.Simulation.CyclesToRun.ToString();

      //  vhdlConversionTargetDropDownList.Enabled = true;

      //  // enable Gezel menu item
      //  gezelToolStripMenuItem.Enabled = true;
      //}
      //else
      //{
      //  // diable VHDL conversion
      //  simulationCyclesTextBox.Enabled = false;
      //  vhdlConversionTargetDropDownList.Enabled = false;

      //  // disable Gezel menu item
      //  gezelToolStripMenuItem.Enabled = false;
      //}
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
      ActionBase.Actions[typeof(ExitApplicationAction)].Execute(sender, e);
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
      // only bind actions if we are not in design mode
      if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
      {
        BindActions();

        // since only top-level controls (forms) have
        // load events, bind contained controls as well
        LayoutControl.ContainerPanel.BindActions();
        LayoutControl.BindActions();
      }

      // load any files 
      openFiles();
    }

    private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

    }

    private void newTextFileToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }
  }
}